package com.ying.dogying.controller;


import cn.hutool.crypto.SecureUtil;
import com.ying.dogying.entity.ImUser;
import com.ying.dogying.entity.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李华明
 * @since 2020-06-05
 */
@Controller
@RequestMapping("/im-user")
public class ImUserController extends BaseController {

    private static final String CAPTCHA_SESSION_KEY = "CAPTCHA_SESSION_KEY";

    /**
     * 进入登录页
     */
    @GetMapping("/login")
    public String login() {
        return "user/login";
    }

    /**
     * 进入注册页
     */
    @GetMapping("/register")
    public String register() {
        return "user/register";
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public @ResponseBody Response doLogin(String username, String password, String captcha) {
    	String text = (String) SecurityUtils.getSubject().getSession().getAttribute(CAPTCHA_SESSION_KEY);
        if(!text.equals(captcha)) {
        	return new Response().failure("验证码不正确.");
        }
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return new Response().failure("用户名或密码不能为空！");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, SecureUtil.md5(password));

        try {
            // login之后会委托给realm完成登录逻辑的认证，可以看看realm的内容(doGetAuthenticationInfo)
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return new Response().failure("用户不存在");
            } else if (e instanceof LockedAccountException) {
                return new Response().failure("用户被禁用");
            } else if (e instanceof IncorrectCredentialsException) {
                return new Response().failure("密码错误");
            } else {
                return new Response().failure("用户认证失败");
            }
        }
        return new Response().success("登录成功").action("/im-main/index");
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public @ResponseBody Response doRegister(ImUser imUser, String captcha, String rePassword) throws IOException {
        String kaptcha = SecurityUtils.getSubject().getSession().getAttribute(CAPTCHA_SESSION_KEY).toString();
        if (!kaptcha.equals(captcha)) {
            return new Response().failure("验证码不正确");
        }
        if (null == rePassword || !rePassword.equals(imUser.getPassword())) {
            return new Response().failure("两次输入密码不一致");
        }
        Response response = imUserService.register(imUser);
        return response.action("login");
    }

    /**
     * 登出
     */
    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }

    /**
     * 更新验证码
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) {
        try {
            //生成文字验证码
            String text = producer.createText();
            //生成图片验证码
            BufferedImage image = producer.createImage(text);
            //把验证码存到shiro的session中
            SecurityUtils.getSubject().getSession().setAttribute(CAPTCHA_SESSION_KEY, text);

            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setContentType("image/jpeg");

            ServletOutputStream outputStream = null;
            outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

}


